template = require 'views/templates/wines_page'
MyPageView = require 'views/base/custom/my_page_view'
Wines = require 'models/wines'
Wine = require 'models/wine'
WinesListView = require './wines_list_view'
WineDetailsView = require './wine_details_view'
DataSources = require 'dataaccess/data_sources'


module.exports = class WinesPageView extends MyPageView
	container: '#page-container'
	template: template
	autoRender: false
	id: "wines-page"
	listContainerName:'.wine-list-container'
	itemContainerName: '.wine-item-details'
	wineDetailsViewName: 'wineDetails'
	wineListViewName: 'winesList'
	winesList:null

	initialize: ->
		console.debug('WinesPageView#initialize-Start')
		@collection = DataSources.GetWines()
		console.debug('WinesPageView#intialize-End')

		super
	
	subscribeToDataSourceEvents: =>
		@modelBind 'add', @closeDetails
		@modelBind 'destroy', @closeDetails
		@modelBind 'change', @onCollectionChanged
		
		
	subscribeToControlsEvents :=>
		@delegate 'click', '.createNewWine', @createNewWine
		@unsubscribeEvent WinesListView.selectedItemEventName, @renderWineDetails 
		@subscribeEvent WinesListView.selectedItemEventName, @renderWineDetails 
		
	render: ->
		console.debug('WinesPageView#render',$(@container),@$el )
		$(@container).html(@$el)
		super


	renderSubviews: ->
		super
		console.debug('WinesPageView#renderSubviews-Start')
		@renderWinesList();


	closeDetails: ->
		@closeSubView @wineDetailsViewName


	onCollectionChanged : =>
		@subscribeToControlsEvents();
		@renderWinesList()


	renderWinesList: =>
		console.debug('WinesPageView#renderWinesList-Start')
		@closeDetails()
		@closeSubView @wineListViewName
		
		@winesList= new WinesListView
			collection: @collection
		@winesList.containerSelector= @listContainerName
		@subview @wineListViewName, @winesList
		@winesList.render();
		

	createNewWine: ->
		console.debug('WinesPageView#createNewWine-Start')
		@renderWineDetails(new Wine());
		console.debug('WinesPageView#createNewWine-End')

	renderWineDetails: (wine) =>
		console.debug('WinesPageView#renderWineDetails-Start' + wine.id)
		view = new WineDetailsView
			model: wine
			container: @$(@itemContainerName)
		@subview @wineDetailsViewName, view
		view.render();
		console.debug('WinesPageView#renderWineDetails-End' + wine.id)


